package cn.stylefeng.guns.modular.hx.basic.service.impl;

import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.modular.basic.model.params.BasicCustomerParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicCustomerResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicXlbOauth2tokenService;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderOutDetailedParam;
import cn.stylefeng.guns.modular.hx.order.model.result.HxOrderOutDetailedResult;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderOutDetailedService;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageStock;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStoragePutDetailedParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.basic.model.params.BasicPutgoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicPutgoodsResult;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.basic.mapper.HxBasicGoodsMapper;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicGoodsCodeParam;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicGoodsParam;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicGoodsCodeResult;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicGoodsResult;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsCodeService;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageStockResult;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageStockService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * <p>
 * 商品信息表 服务实现类
 * </p>
 *
 * @author zhucx
 * @since 2023-06-18
 */
@Service
public class HxBasicGoodsServiceImpl extends ServiceImpl<HxBasicGoodsMapper, HxBasicGoods> implements HxBasicGoodsService {
    @Autowired
    private HxOrderOutDetailedService hxOrderOutDetailedService;
    @Override
    public void add(HxBasicGoodsParam param){
        HxBasicGoods entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(HxBasicGoodsParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(HxBasicGoodsParam param){
        HxBasicGoods oldEntity = getOldEntity(param);
        HxBasicGoods newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public HxBasicGoodsResult findBySpec(HxBasicGoodsParam param,Long operateId){
        return this.baseMapper.findBySpec(param,operateId);
    }

    @Override
    public List<HxBasicGoodsResult> findListBySpec(HxBasicGoodsParam param){
        return this.baseMapper.findListBySpec(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(HxBasicGoodsParam param,String condition,Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition,operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfo findYpdwPageBySpec(HxBasicGoodsParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customYpdwPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfo findGjkcWgxPageBySpec(HxBasicGoodsParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customGjkcWgxPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }



    private Serializable getKey(HxBasicGoodsParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private HxBasicGoods getOldEntity(HxBasicGoodsParam param) {
        return this.getById(getKey(param));
    }

    private HxBasicGoods getEntity(HxBasicGoodsParam param) {
        HxBasicGoods entity = new HxBasicGoods();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

	@Override
	public boolean saveBatchList(List<HxBasicGoodsParam> list) {
		return this.baseMapper.saveBatchList(list);
	}
	
	private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }

    @Resource
    private HxBasicGoodsCodeService hxBasicGoodsCodeService;

	@Override
	public ResponseData getExceldataUpdate(MultipartFile file, HxBasicGoodsParam hxBasicGoodsParam, ResponseData data) throws Exception {
		if (ToolUtil.isEmpty(hxBasicGoodsParam.getGoodsCustomerId())) {
			data.setSuccess(false);
			data.setMessage("Please Select Customer");
			return data;
		}
		
		String fileName = file.getOriginalFilename();
		
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("上传文件格式不正确");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);

		Map<String, HxBasicGoodsResult> goodsMap = new HashMap<>();
		HxBasicGoodsParam hxgoodsp = new HxBasicGoodsParam();
		hxgoodsp.setGoodsCustomerId(hxBasicGoodsParam.getGoodsCustomerId());
		List<HxBasicGoodsResult> hxp = this.findListBySpec(hxgoodsp);
		for (HxBasicGoodsResult pr : hxp) {
			goodsMap.put(pr.getGoodsNumber(), pr);
		}

		Map<String, HxBasicGoodsCodeResult> goodsCodeMap = new HashMap<>();
		HxBasicGoodsCodeParam goodsCodep = new HxBasicGoodsCodeParam();
		goodsCodep.setDeptId(hxBasicGoodsParam.getDeptId());
		goodsCodep.setDeliverId(hxBasicGoodsParam.getDeliverId());
		goodsCodep.setOperateId(hxBasicGoodsParam.getOperateId());
		List<HxBasicGoodsCodeResult> hxgcp = hxBasicGoodsCodeService.findListBySpec(goodsCodep);
		for (HxBasicGoodsCodeResult pr : hxgcp) {
			goodsCodeMap.put(pr.getCodeName(), pr);
		}
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            HxBasicGoodsResult  basicGoodsResult = new HxBasicGoodsResult();
            BigDecimal goodsVolumes = new BigDecimal("0");
            BigDecimal goodsWeights = new BigDecimal("0");
            BigDecimal goodsChargingPss = new BigDecimal("0");
            BigDecimal goodsChargingCgs = new BigDecimal("0");
            BigDecimal cgRate1 = new BigDecimal("0");
            HxBasicGoodsParam goodsParam = new HxBasicGoodsParam();

            String  goodsName = getCellValue(row.getCell(0));
            if (ToolUtil.isNotEmpty(goodsName)) {
            	goodsParam.setGoodsName(goodsName);//商品名称
			} 
            
            String  goodsNumber = getCellValue(row.getCell(1));
            if (ToolUtil.isNotEmpty(goodsNumber)) {
            	basicGoodsResult = goodsMap.get(goodsNumber);
            	if (basicGoodsResult != null) {
            		goodsParam.setId(basicGoodsResult.getId());
				} else {
					continue;
				}
			} else {
                break;
			}

            String  goodsPcode69 = getCellValue(row.getCell(2));//商品码
            if (ToolUtil.isNotEmpty(goodsPcode69)) {
            	goodsParam.setGoodsPcode69(goodsPcode69);
			}

            String  goodsXcode69 = getCellValue(row.getCell(3));//商品码2
            if (ToolUtil.isNotEmpty(goodsXcode69)) {
            	goodsParam.setGoodsXcode69(goodsXcode69);
			}

            String  goodsHcode69 = getCellValue(row.getCell(4));//商品码3
            if (ToolUtil.isNotEmpty(goodsHcode69)) {
                goodsParam.setGoodsHcode69(goodsHcode69);
            }

            String  goodsSpecs = getCellValue(row.getCell(5));
            if (ToolUtil.isNotEmpty(goodsSpecs)) {
            	goodsParam.setGoodsSpecs(goodsSpecs);
			}

            String  goodsBigtype = getCellValue(row.getCell(6));//分类
            if (ToolUtil.isNotEmpty(goodsBigtype)) {
            	goodsParam.setGoodsBigtype(goodsBigtype);
            	
            	HxBasicGoodsCodeResult  codeResult = goodsCodeMap.get(goodsBigtype);
            	if(codeResult != null) {
            		goodsParam.setGoodsBigtypedictId(Long.parseLong(codeResult.getId().toString()));
            	} else {
            		goodsParam.setGoodsBigtypedictId(0l);
            	}
			}

            String  goodsBrand = getCellValue(row.getCell(7));//品牌
            if (ToolUtil.isNotEmpty(goodsBrand)) {
            	goodsParam.setGoodsBrand(goodsBrand);
			}

            String  jibenUnit = getCellValue(row.getCell(8));
            if (ToolUtil.isNotEmpty(jibenUnit)) {
                goodsParam.setJibenUnit(jibenUnit);
            }

            String  kcUnit = getCellValue(row.getCell(9));
            if (ToolUtil.isNotEmpty(kcUnit)) {
                goodsParam.setKcUnit(kcUnit);
            }

            String  kcRate = getCellValue(row.getCell(10));
            if (ToolUtil.isNotEmpty(kcRate)) {
                BigDecimal kcRateb = new BigDecimal(kcRate).setScale(2,BigDecimal.ROUND_DOWN);
                goodsParam.setKcRate(kcRateb.toString());
            }

            String  cgUnit = getCellValue(row.getCell(11));
            if (ToolUtil.isNotEmpty(cgUnit)) {
                goodsParam.setCgUnit(cgUnit);
            }

            String  cgRate = getCellValue(row.getCell(12));
            if (ToolUtil.isNotEmpty(cgRate)) {
                cgRate1 = new BigDecimal(cgRate).setScale(2,BigDecimal.ROUND_DOWN);
                BigDecimal cgRateb = new BigDecimal(cgRate).setScale(2,BigDecimal.ROUND_DOWN);
                goodsParam.setCgRate(cgRateb.toString());
            } else {
                cgRate1 = new BigDecimal(basicGoodsResult.getCgRate()).setScale(2,BigDecimal.ROUND_DOWN);
            }

            String  pfUnit = getCellValue(row.getCell(13));
            if (ToolUtil.isNotEmpty(pfUnit)) {
                goodsParam.setPfUnit(pfUnit);
            }

            String  pfRate = getCellValue(row.getCell(14));
            if (ToolUtil.isNotEmpty(pfRate)) {
                BigDecimal pfRateb = new BigDecimal(pfRate).setScale(2,BigDecimal.ROUND_DOWN);
                goodsParam.setPfRate(pfRateb.toString());
            }

            String  psUnit = getCellValue(row.getCell(15));
            if (ToolUtil.isNotEmpty(psUnit)) {
                goodsParam.setPsUnit(psUnit);
            }

            String  psRate = getCellValue(row.getCell(16));
            if (ToolUtil.isNotEmpty(psRate)) {
                BigDecimal psRateb = new BigDecimal(psRate).setScale(2,BigDecimal.ROUND_DOWN);
                goodsParam.setPsRate(psRateb.toString());
            }
            
            String  goodsBottom = getCellValue(row.getCell(17));
            if (ToolUtil.isNotEmpty(goodsBottom)) {
            	goodsParam.setGoodsBottom(goodsBottom);//底
			} 
            
            String  goodsLamination = getCellValue(row.getCell(18));
            if (ToolUtil.isNotEmpty(goodsLamination)) {
            	goodsParam.setGoodsLamination(goodsLamination);//叠层
			} 
            
            String  goodsSupportvolume = getCellValue(row.getCell(19));
            if (ToolUtil.isNotEmpty(goodsSupportvolume)) {
            	goodsParam.setGoodsSupportvolume(goodsSupportvolume);//每托存量
			} 
            
            String  goodsTraylayer = getCellValue(row.getCell(20));
            if (ToolUtil.isNotEmpty(goodsTraylayer)) {
            	goodsParam.setGoodsTraylayer(goodsTraylayer);//托层
			} 
            
            String  length = getCellValue(row.getCell(21));
            if (ToolUtil.isNotEmpty(length)) {
            	goodsParam.setLength(length);
			} 
            
            String  width = getCellValue(row.getCell(22));
            if (ToolUtil.isNotEmpty(width)) {
            	goodsParam.setWidth(width);
			} 
            
            String  height = getCellValue(row.getCell(23));
            if (ToolUtil.isNotEmpty(height)) {
            	goodsParam.setHeight(height);
			} 
            
            String  goodsVolume = getCellValue(row.getCell(24));
            if (ToolUtil.isNotEmpty(goodsVolume)) {
                goodsVolumes = new BigDecimal(goodsVolume).setScale(4,BigDecimal.ROUND_DOWN);
            	BigDecimal v = new BigDecimal(goodsVolume).setScale(4,BigDecimal.ROUND_DOWN);
            	goodsParam.setGoodsVolume(v.toString());//采购体积
			} else {
                goodsVolumes = new BigDecimal(basicGoodsResult.getGoodsVolume()).setScale(4,BigDecimal.ROUND_DOWN);;
            }

            String  goodsWeight = getCellValue(row.getCell(25));
            if (ToolUtil.isNotEmpty(goodsWeight)) {
                goodsWeights = new BigDecimal(goodsWeight).setScale(3,BigDecimal.ROUND_DOWN);
            	BigDecimal w = new BigDecimal(goodsWeight).setScale(3,BigDecimal.ROUND_DOWN);
            	goodsParam.setGoodsWeight(w.toString());//采购重量.
			} else{
                goodsWeights = new BigDecimal(basicGoodsResult.getGoodsVolume()).setScale(4,BigDecimal.ROUND_DOWN);;
            }
            
            String  goodsChargingCg = getCellValue(row.getCell(26));
            if (ToolUtil.isNotEmpty(goodsChargingCg)) {
                goodsChargingCgs = new BigDecimal(goodsChargingCg).setScale(3,BigDecimal.ROUND_DOWN);
            	BigDecimal p = new BigDecimal(goodsChargingCg).setScale(3,BigDecimal.ROUND_DOWN);
            	goodsParam.setGoodsChargingCg(p.toString());//采购价
			} else {
                goodsChargingCgs = new BigDecimal(basicGoodsResult.getGoodsChargingCg()).setScale(4,BigDecimal.ROUND_DOWN);;
            }
            
            String  goodsChargingPs = getCellValue(row.getCell(27));
            if (ToolUtil.isNotEmpty(goodsChargingPs)) {
                goodsChargingPss = new BigDecimal(goodsChargingPs).setScale(3,BigDecimal.ROUND_DOWN);
            	BigDecimal p = new BigDecimal(goodsChargingPs).setScale(3,BigDecimal.ROUND_DOWN);
            	goodsParam.setGoodsChargingPs(p.toString());//配送价
			} else {
                goodsChargingPss = new BigDecimal(basicGoodsResult.getGoodsChargingPs()).setScale(4,BigDecimal.ROUND_DOWN);;
            }
            
            String  goodsChargingPf = getCellValue(row.getCell(28));
            if (ToolUtil.isNotEmpty(goodsChargingPf)) {
            	BigDecimal p = new BigDecimal(goodsChargingPf).setScale(3,BigDecimal.ROUND_DOWN);
            	goodsParam.setGoodsChargingPf(p.toString());//批发价
			} 

            String  goodsWarranty = getCellValue(row.getCell(29));
            if (ToolUtil.isNotEmpty(goodsWarranty)) {
            	goodsParam.setGoodsWarranty(goodsWarranty);//保质期
			} 
            
            String  anquanNum = getCellValue(row.getCell(30));
            if (ToolUtil.isNotEmpty(anquanNum)) {
            	BigDecimal p = new BigDecimal(anquanNum).setScale(3,BigDecimal.ROUND_DOWN);
            	goodsParam.setAnquanNum(p.toString());
			} 

            String  dismantlingParts = getCellValue(row.getCell(31));
            if (ToolUtil.isNotEmpty(dismantlingParts)) {
                goodsParam.setDismantlingParts(dismantlingParts);
            }

            String  goodsNodes = getCellValue(row.getCell(32));
            if (ToolUtil.isNotEmpty(goodsNodes)) {
            	goodsParam.setGoodsNodes(goodsNodes);
			} 
            this.update(goodsParam);

            if(ToolUtil.isNotEmpty(goodsVolume)||ToolUtil.isNotEmpty(goodsWeight)||ToolUtil.isNotEmpty(goodsChargingPs)){
                //更新待提交出库订单 体积、重量、金额
                HxOrderOutDetailedParam detailedParam = new HxOrderOutDetailedParam();
                detailedParam.setGoodsId(Long.parseLong(goodsParam.getId().toString()));
                List<HxOrderOutDetailedResult> odlist = hxOrderOutDetailedService.finddtjListBySpec(detailedParam);
                for (HxOrderOutDetailedResult r1 : odlist) {
                    BigDecimal ratiobig = new BigDecimal(r1.getRate());
                    BigDecimal goodsPrice = ratiobig.multiply(goodsChargingPss).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                    BigDecimal quantitybig = new BigDecimal(r1.getPsNum());
                    if (ratiobig.compareTo(cgRate1) == -1) {
                        // 如果配送换算率小于采购换算率
                        BigDecimal div = cgRate1.divide(ratiobig, 3, BigDecimal.ROUND_HALF_DOWN);
                        BigDecimal divv_v = goodsVolumes.divide(div, 4, BigDecimal.ROUND_HALF_DOWN);
                        goodsVolumes = divv_v;
                        BigDecimal divv_w = goodsWeights.divide(div, 3, BigDecimal.ROUND_HALF_DOWN);
                        goodsWeights = divv_w;
                    } else if (ratiobig.compareTo(cgRate1) == 1) {
                        // 如果配送换算率大于采购换算率
                        BigDecimal div = ratiobig.divide(cgRate1, 3, BigDecimal.ROUND_HALF_DOWN);
                        BigDecimal divv_v = goodsVolumes.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
                        goodsVolumes = divv_v;
                        BigDecimal divv_w = goodsWeights.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                        goodsWeights = divv_w;
                    }
                    HxOrderOutDetailedParam detailedParamupdate = new HxOrderOutDetailedParam();
                    detailedParamupdate.setId(r1.getId());
                    detailedParamupdate.setGoodsWeight(goodsWeights.setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                    detailedParamupdate.setOutWeight(quantitybig.multiply(goodsWeights).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                    detailedParamupdate.setGoodsVolume(goodsVolumes.setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
                    detailedParamupdate.setOutVolume(quantitybig.multiply(goodsVolumes).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
                    detailedParamupdate.setGoodsPrice(goodsPrice.toString());
                    detailedParamupdate.setOutMoney(quantitybig.multiply(goodsPrice).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                    hxOrderOutDetailedService.update(detailedParamupdate);
                }
            }

            if(ToolUtil.isNotEmpty(goodsVolume)||ToolUtil.isNotEmpty(goodsWeight)||ToolUtil.isNotEmpty(goodsChargingCg)){
                //更新库存 体积、重量、金额
                HxStorageStockParam hxStorageStockParam = new HxStorageStockParam();
                hxStorageStockParam.setCustomerId(Long.parseLong(hxBasicGoodsParam.getGoodsCustomerId().toString()));
                hxStorageStockParam.setGoodsId(Long.parseLong(goodsParam.getId().toString()));
                List<HxStorageStockResult> slist = hxStorageStockService.findListBySpec(hxStorageStockParam);
                for (HxStorageStockResult sr : slist) {
                    BigDecimal ratiobig = new BigDecimal(sr.getKcRate());
                    BigDecimal goodsPrice = ratiobig.multiply(goodsChargingCgs).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                    BigDecimal quantitybig = new BigDecimal(sr.getKcNum());
                    if(ratiobig.compareTo(cgRate1) == -1) {
                        //如果配送换算率 小于 采购换算率：  配送体积  =  采购体积/（采购换算率/配送换算率）
                        BigDecimal div = cgRate1.divide(ratiobig,3, BigDecimal.ROUND_HALF_DOWN);
                        BigDecimal divv_v = goodsVolumes.divide(div,4, BigDecimal.ROUND_HALF_DOWN);
                        goodsVolumes = divv_v;
                        BigDecimal divv_w = goodsWeights.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
                        goodsWeights = divv_w;
                    }
                    if(ratiobig.compareTo(cgRate1) == 1) {
                        //如果配送换算率 大于 采购换算率：  配送体积  =  采购体积*（配送换算率/采购换算率）
                        BigDecimal div = ratiobig.divide(cgRate1,3, BigDecimal.ROUND_HALF_DOWN);
                        BigDecimal divv_v = goodsVolumes.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
                        goodsVolumes = divv_v;
                        BigDecimal divv_w = goodsWeights.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                        goodsWeights = divv_w;
                    }

                    HxStorageStockParam detailedParamupdate = new HxStorageStockParam();
                    detailedParamupdate.setId(sr.getId());
                    detailedParamupdate.setGoodsWeight(goodsWeight.toString());
                    detailedParamupdate.setStockWeight(quantitybig.multiply(goodsWeights).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                    detailedParamupdate.setGoodsVolume(goodsVolume.toString());
                    detailedParamupdate.setStockVolume(quantitybig.multiply(goodsVolumes).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
                    detailedParamupdate.setGoodsPrice(goodsPrice.toString());
                    detailedParamupdate.setStockMoney(quantitybig.multiply(goodsPrice).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                    hxStorageStockService.update(detailedParamupdate);
                }
            }
        }
        data.setSuccess(true);
		return data;
	}

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=150)
	public ResponseData getExceldata(MultipartFile file, HxBasicGoodsParam hxBasicGoodsParam, ResponseData data) throws Exception {
		if (ToolUtil.isEmpty(hxBasicGoodsParam.getGoodsCustomerId()) || ToolUtil.isEmpty(hxBasicGoodsParam.getGoodsCustomerName())) {
			data.setSuccess(false);
			data.setMessage("Please Select Customer");
			return data;
		}
		
		String fileName = file.getOriginalFilename();
		List<HxBasicGoods> list = new ArrayList<HxBasicGoods>();
		
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("上传文件格式不正确");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);

		Map<String, HxBasicGoodsResult> goodsMap = new HashMap<>();
		HxBasicGoodsParam hxgoodsp = new HxBasicGoodsParam();
		hxgoodsp.setGoodsCustomerId(hxBasicGoodsParam.getGoodsCustomerId());
		List<HxBasicGoodsResult> hxp = this.findListBySpec(hxgoodsp);
		for (HxBasicGoodsResult pr : hxp) {
			goodsMap.put(pr.getGoodsNumber(), pr);
		}

		Map<String, HxBasicGoodsCodeResult> goodsCodeMap = new HashMap<>();
		HxBasicGoodsCodeParam goodsCodep = new HxBasicGoodsCodeParam();
		goodsCodep.setDeptId(hxBasicGoodsParam.getDeptId());
		goodsCodep.setDeliverId(hxBasicGoodsParam.getDeliverId());
		goodsCodep.setOperateId(hxBasicGoodsParam.getOperateId());
		List<HxBasicGoodsCodeResult> hxgcp = hxBasicGoodsCodeService.findListBySpec(goodsCodep);
		for (HxBasicGoodsCodeResult pr : hxgcp) {
			goodsCodeMap.put(pr.getCodeName(), pr);
		}
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            HxBasicGoods goodsParam = new HxBasicGoods();
            goodsParam.setDeptId(hxBasicGoodsParam.getDeptId());
            goodsParam.setDeliverId(hxBasicGoodsParam.getDeliverId());
            goodsParam.setGoodsCustomerId(hxBasicGoodsParam.getGoodsCustomerId());
            goodsParam.setGoodsCustomerName(hxBasicGoodsParam.getGoodsCustomerName());
            goodsParam.setCreateTime(new Date());
            goodsParam.setCreateName(hxBasicGoodsParam.getCreateName());

            String  goodsName = getCellValue(row.getCell(0));
            if (ToolUtil.isNotEmpty(goodsName)) {
            	goodsParam.setGoodsName(goodsName);//商品名称
			} else {
                continue;
			}
            
            String  goodsNumber = getCellValue(row.getCell(1));
            if (ToolUtil.isNotEmpty(goodsNumber)) {
            	HxBasicGoodsResult  basicGoodsResult = goodsMap.get(goodsNumber);
            	if (basicGoodsResult == null) {
            		goodsParam.setGoodsNumber(goodsNumber);//商品编号
				} else {
					continue;
				}
			} else {
                break;
			}

            String  goodsPcode69 = getCellValue(row.getCell(2));//商品码
            if (ToolUtil.isNotEmpty(goodsPcode69)) {
            	goodsParam.setGoodsPcode69(goodsPcode69);
			}

            String  goodsXcode69 = getCellValue(row.getCell(3));//商品码2
            if (ToolUtil.isNotEmpty(goodsXcode69)) {
            	goodsParam.setGoodsXcode69(goodsXcode69);
			}

            String  goodsHcode69 = getCellValue(row.getCell(4));//商品码3
            if (ToolUtil.isNotEmpty(goodsHcode69)) {
                goodsParam.setGoodsHcode69(goodsHcode69);
            }

            String  goodsSpecs = getCellValue(row.getCell(5));
            if (ToolUtil.isNotEmpty(goodsSpecs)) {
            	goodsParam.setGoodsSpecs(goodsSpecs);
			}

            String  goodsBigtype = getCellValue(row.getCell(6));//分类
            if (ToolUtil.isNotEmpty(goodsBigtype)) {
            	goodsParam.setGoodsBigtype(goodsBigtype);
            	
            	HxBasicGoodsCodeResult  codeResult = goodsCodeMap.get(goodsBigtype);
            	if(codeResult != null) {
            		goodsParam.setGoodsBigtypedictId(Long.parseLong(codeResult.getId().toString()));
            	} else {
            		goodsParam.setGoodsBigtypedictId(0l);
            	}
			}

            String  goodsBrand = getCellValue(row.getCell(7));//品牌
            if (ToolUtil.isNotEmpty(goodsBrand)) {
            	goodsParam.setGoodsBrand(goodsBrand);
			}

            String  jibenUnit = getCellValue(row.getCell(8));
            if (ToolUtil.isNotEmpty(jibenUnit)) {
            	goodsParam.setJibenUnit(jibenUnit);
			}

            String  kcUnit = getCellValue(row.getCell(9));
            if (ToolUtil.isNotEmpty(kcUnit)) {
            	goodsParam.setKcUnit(kcUnit);
			}

            String  kcRate = getCellValue(row.getCell(10));
            if (ToolUtil.isNotEmpty(kcRate)) {
            	BigDecimal kcRateb = new BigDecimal(kcRate).setScale(2,BigDecimal.ROUND_DOWN);
            	goodsParam.setKcRate(kcRateb.toString());
			}

            String  cgUnit = getCellValue(row.getCell(11));
            if (ToolUtil.isNotEmpty(cgUnit)) {
            	goodsParam.setCgUnit(cgUnit);
			}

            String  cgRate = getCellValue(row.getCell(12));
            if (ToolUtil.isNotEmpty(cgRate)) {
            	BigDecimal cgRateb = new BigDecimal(cgRate).setScale(2,BigDecimal.ROUND_DOWN);
            	goodsParam.setCgRate(cgRateb.toString());
			}

            String  pfUnit = getCellValue(row.getCell(13));
            if (ToolUtil.isNotEmpty(pfUnit)) {
            	goodsParam.setPfUnit(pfUnit);
			}

            String  pfRate = getCellValue(row.getCell(14));
            if (ToolUtil.isNotEmpty(pfRate)) {
            	BigDecimal pfRateb = new BigDecimal(pfRate).setScale(2,BigDecimal.ROUND_DOWN);
            	goodsParam.setPfRate(pfRateb.toString());
			}

            String  psUnit = getCellValue(row.getCell(15));
            if (ToolUtil.isNotEmpty(psUnit)) {
            	goodsParam.setPsUnit(psUnit);
			}

            String  psRate = getCellValue(row.getCell(16));
            if (ToolUtil.isNotEmpty(psRate)) {
            	BigDecimal psRateb = new BigDecimal(psRate).setScale(2,BigDecimal.ROUND_DOWN);
            	goodsParam.setPsRate(psRateb.toString());
			}
            
            String  goodsBottom = getCellValue(row.getCell(17));
            if (ToolUtil.isNotEmpty(goodsBottom)) {
            	goodsParam.setGoodsBottom(goodsBottom);//底
			} else {
            	goodsParam.setGoodsSupportvolume("10");//底
			}
            
            String  goodsLamination = getCellValue(row.getCell(18));
            if (ToolUtil.isNotEmpty(goodsLamination)) {
            	goodsParam.setGoodsLamination(goodsLamination);//叠层
			} else {
            	goodsParam.setGoodsLamination("10");//叠层
			}
            
            String  goodsSupportvolume = getCellValue(row.getCell(19));
            if (ToolUtil.isNotEmpty(goodsSupportvolume)) {
            	goodsParam.setGoodsSupportvolume(goodsSupportvolume);//每托存量
			} else {
            	goodsParam.setGoodsSupportvolume("100");//每托存量
			}
            
            String  goodsTraylayer = getCellValue(row.getCell(20));
            if (ToolUtil.isNotEmpty(goodsTraylayer)) {
            	goodsParam.setGoodsTraylayer(goodsTraylayer);//托层
			} else {
            	goodsParam.setGoodsTraylayer("1");//托层
			}
            
            String  length = getCellValue(row.getCell(21));
            if (ToolUtil.isNotEmpty(length)) {
            	goodsParam.setLength(length);
			} 
            
            String  width = getCellValue(row.getCell(22));
            if (ToolUtil.isNotEmpty(width)) {
            	goodsParam.setWidth(width);
			} 
            
            String  height = getCellValue(row.getCell(23));
            if (ToolUtil.isNotEmpty(height)) {
            	goodsParam.setHeight(height);
			} 
            
            String  goodsVolume = getCellValue(row.getCell(24));
            if (ToolUtil.isNotEmpty(goodsVolume)) {
            	BigDecimal v = new BigDecimal(goodsVolume).setScale(4,BigDecimal.ROUND_DOWN);
            	goodsParam.setGoodsVolume(v.toString());//采购体积
			} else {
            	goodsParam.setGoodsVolume("0.1");//采购体积
			}




            String  goodsWeight = getCellValue(row.getCell(25));
            if (ToolUtil.isNotEmpty(goodsWeight)) {
            	BigDecimal w = new BigDecimal(goodsWeight).setScale(3,BigDecimal.ROUND_DOWN);
            	goodsParam.setGoodsWeight(w.toString());//采购重量
			} else {
            	goodsParam.setGoodsWeight("0.1");//采购重量
			}
            
            String  goodsChargingCg = getCellValue(row.getCell(26));
            if (ToolUtil.isNotEmpty(goodsChargingCg)) {
            	BigDecimal p = new BigDecimal(goodsChargingCg).setScale(3,BigDecimal.ROUND_DOWN);
            	goodsParam.setGoodsChargingCg(p.toString());//采购价
			} else {
            	goodsParam.setGoodsChargingCg("10");//采购价
			}
            
            String  goodsChargingPs = getCellValue(row.getCell(27));
            if (ToolUtil.isNotEmpty(goodsChargingPs)) {
            	BigDecimal p = new BigDecimal(goodsChargingPs).setScale(3,BigDecimal.ROUND_DOWN);
            	goodsParam.setGoodsChargingPs(p.toString());//配送价
			} else {
            	goodsParam.setGoodsChargingPs("10");//配送价
			}
            
            String  goodsChargingPf = getCellValue(row.getCell(28));
            if (ToolUtil.isNotEmpty(goodsChargingPf)) {
            	BigDecimal p = new BigDecimal(goodsChargingPf).setScale(3,BigDecimal.ROUND_DOWN);
            	goodsParam.setGoodsChargingPf(p.toString());//批发价
			} else {
            	goodsParam.setGoodsChargingPf("10");//批发价
			}

            String  goodsWarranty = getCellValue(row.getCell(29));
            if (ToolUtil.isNotEmpty(goodsWarranty)) {
            	goodsParam.setGoodsWarranty(goodsWarranty);//保质期
			} else {
            	goodsParam.setGoodsWarranty("36");//保质期
			}
            
            String  anquanNum = getCellValue(row.getCell(30));
            if (ToolUtil.isNotEmpty(anquanNum)) {
            	BigDecimal p = new BigDecimal(anquanNum).setScale(3,BigDecimal.ROUND_DOWN);
            	goodsParam.setAnquanNum(p.toString());
			} else {
            	goodsParam.setAnquanNum("14");
			}

            String  dismantlingParts = getCellValue(row.getCell(31));
            if (ToolUtil.isNotEmpty(dismantlingParts)) {
                goodsParam.setDismantlingParts(dismantlingParts);
            }

            String  goodsNodes = getCellValue(row.getCell(32));
            if (ToolUtil.isNotEmpty(goodsNodes)) {
            	goodsParam.setGoodsNodes(goodsNodes);
			} 
            list.add(goodsParam);
            if(list.size() == 500) {
                //保存到库存表
                this.saveBatch(list);
                list = new ArrayList<HxBasicGoods>();
            }
        }
        if (list.size() > 0) {
        	saveBatch(list);
		}
        data.setSuccess(true);
		return data;
	}

    @Override
    public LayuiPageInfo findOneBySpec(HxBasicGoodsParam basicGoodsParam, String condition, Long operateId) {
        Page pageContext = getPageContext();
        Page<HxBasicGoodsResult> page = this.baseMapper.customPageList(pageContext, basicGoodsParam, condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public List<HxBasicGoodsResult> findListBySpecAppOut(HxBasicGoodsParam goodsParam, String condition, Long operateId) {
        return this.baseMapper.findListBySpecAppOut(goodsParam,condition,operateId);
    }


    @Autowired
    private HxStorageStockService hxStorageStockService;

    @Override
    public ResponseData gcjy(HxStorageStockParam hxStorageStockParam) {
        List<HxStorageStockResult> list = hxStorageStockService.list(hxStorageStockParam);
            for (HxStorageStockResult item : list) {
                if (Double.parseDouble(item.getKcNum()) >= 0) {
                    return ResponseData.error("还剩有库存");
                }
            }
       return ResponseData.success();
    }

	@Override
	public List<HxBasicGoodsResult> findlistAllBySpec(HxBasicGoodsParam hxBasicGoodsParam, String condition,
			Long operateId) {
		return this.baseMapper.findlistAllBySpec(hxBasicGoodsParam,condition,operateId);
	}
    @Resource
    private BasicCustomerService basicCustomerService;
    @Resource
    private HxBasicGoodsService hxBasicGoodsService;
    @Resource
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    @Override
    public void taskAppointment2() {
        BasicCustomerParam param = new BasicCustomerParam();
        List <BasicCustomerResult> basicCustomerResult = basicCustomerService.findpullReturnXlbgoodsListBySpec(param);
        for (BasicCustomerResult r : basicCustomerResult) {

            if (r.getModeTms().equals("3")){
                HxBasicGoodsParam hxBasicGoodsParam1 = new HxBasicGoodsParam();
                hxBasicGoodsParam1.setGoodsCustomerId(r.getId());
                List<HxBasicGoodsResult> list = hxBasicGoodsService.findListBySpec(hxBasicGoodsParam1);
                //System.out.println("=================list:执行任务1=");

                //      String url = "https://test-api.xlbsoft.com/api/hxl.open.item.findbyupdatetime";
                String url = "https://hxl-api.xlbsoft.com/api/hxl.open.item.findbyupdatetime";

                // 创建订单数组
                JSONArray ordersArray = new JSONArray();

                // 创建订单对象
                JSONObject orderObject = new JSONObject();
                orderObject.put("direction", "ASC");
                orderObject.put("property", "id");

                // 将订单对象添加到订单数组中
                ordersArray.put(orderObject);

                // 创建请求参数对象
                JSONObject json = new JSONObject();
                json.put("orders", ordersArray);
                json.put("page_number", 1);
                json.put("page_size", 200);
                json.put("update_time", "");


                BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
                oauth2tokenParam.setDeliverId(r.getDeliverId());
                oauth2tokenParam.setGsnumber(r.getGsnumber());
                BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);

                String response = HttpRequest.post(url)
                        .header("Authorization", "Bearer "+oauth2tokenResult.getOauth2TokenXlb())
                        .body(json.toString()).execute().body();
                JSONObject jsonObject = new JSONObject(response);
                List<HxBasicGoods> batchToAdd = new ArrayList<>();

                if (jsonObject.get("code").toString().equals("0")) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    Object totalElements = ((JSONObject) data).get("total_elements");// 总商品数
                    Object totalPages = ((JSONObject) data).get("total_pages");//总页数

                    int pageNumber = 0; // 初始页号

//                    Map<String, HxBasicGoodsCodeResult> goodsCodeMap = new HashMap<>();
//                    HxBasicGoodsCodeParam goodsCodep = new HxBasicGoodsCodeParam();
//                    goodsCodep.setDeptId(r.getDeptId());
//                    goodsCodep.setDeliverId(r.getDeliverId());
//                    goodsCodep.setOperateId((long)r.getCustomerOperateId());
//                    List<HxBasicGoodsCodeResult> hxgcp = hxBasicGoodsCodeService.findListBySpec(goodsCodep);
//                    for (HxBasicGoodsCodeResult pr : hxgcp) {
//                        if(ToolUtil.isNotEmpty(pr.getXlbCategoryId())) {
//                            goodsCodeMap.put(pr.getXlbCategoryId(), pr);
//                        }
//                    }
                    for (int i = 0; i < (int)totalPages; i++) {

                        pageNumber++; // 增加页号，请求下一页数据
                        // 创建请求参数对象
                        JSONObject jsons = new JSONObject();
                        jsons.put("orders", ordersArray);
                        jsons.put("page_number", i);
                        jsons.put("page_size", 200);
                        jsons.put("update_time", "");

                        String post = HttpRequest.post(url)
                                .header("Authorization", "Bearer "+oauth2tokenResult.getOauth2TokenXlb())
                                .body(jsons.toString()).execute().body();
                        JSONObject object = new JSONObject(post);
                        //System.out.println("================jsons："+jsons+"========================");
                        //System.out.println("================post："+post+"========================");

                        Object data1 = object.opt("data");

                        JSONArray content  = ((JSONObject) data1).getJSONArray("content");// 商品明细

                        if (content.length() > 0) {
                            for (Object contents: content){
                                HxBasicGoods hxBasicGoodsParam=new HxBasicGoods();
                                Object  basicHeight= ((JSONObject) contents).get("basic_height");// 基本单位高度
                                Object  basicLength= ((JSONObject) contents).get("basic_length");// 基本单位长度
                                Object  basicWidth= ((JSONObject) contents).get("basic_width");// 基本单位宽度
                                Object  categoryId= ((JSONObject) contents).get("category_id");// 商品分类id



                                Object  code= ((JSONObject) contents).get("code");// 商品代码
                                Object  barCode= ((JSONObject) contents).get("bar_code");// 商品条码
                                Object  createTime= ((JSONObject) contents).get("create_time");// 创建时间
                                Object  dateInType= ((JSONObject) contents).get("date_in_type");// 日期录入规则: 0-无日期 1-生产日期 2-到期日期
                                Object  expireType= ((JSONObject) contents).get("expire_type");//保质期类型：1-按天数 2-按月份
                                Object  expireTypeNum= ((JSONObject) contents).get("expire_type_num");// 保质期天数或月数
                                Object  grossWeight= ((JSONObject) contents).get("gross_weight");// 毛重
                                Object  height= ((JSONObject) contents).get("height");// 商品高度
                                Object  id= ((JSONObject) contents).get("id");// 商品id
                                Object  length= ((JSONObject) contents).get("length");//商品长度
                                Object  name= ((JSONObject) contents).get("name");// 商品名称
                                Object  netWeight= ((JSONObject) contents).get("net_weight");// 净重
                                Object  period= ((JSONObject) contents).get("period");// 保质期
                                Object  unit= ((JSONObject) contents).get("unit");//基本单位
                                Object  updateTime1= ((JSONObject) contents).get("update_time");//修后修改时间
                                Object  volume= ((JSONObject) contents).get("volume");// 商品体积
                                Object  weigh= ((JSONObject) contents).get("weigh");// 是否称重
                                Object  width= ((JSONObject) contents).get("width");//商品宽度
                                Object  weightSpec= ((JSONObject) contents).get("purchase_spec");//规格
                                Object purchaseRatio = ((JSONObject) contents).get("purchase_ratio");//采购单位换算率
                                Object purchaseUnit = ((JSONObject) contents).get("purchase_unit");//采购单位
                                Object purchasePrice = ((JSONObject) contents).get("purchase_price");//采购价
                                Object deliveryRatio = ((JSONObject) contents).get("delivery_ratio");//配送单位换算率
                                Object deliveryUnit = ((JSONObject) contents).get("delivery_unit");//配送单位
                                Object deliveryPrice = ((JSONObject) contents).get("delivery_price");//配送价
                                Object wholesaleRatio = ((JSONObject) contents).get("wholesale_ratio");//批发单位换算率
                                Object wholesaleUnit = ((JSONObject) contents).get("wholesale_unit");//批发单位
                                Object wholesalePrice = ((JSONObject) contents).get("wholesale_price");//批发价
                                Object purchaseVolume = ((JSONObject) contents).get("purchase_volume");//采购体积


                                Object stockRatio = ((JSONObject) contents).get("stock_ratio");//库存单位换算率
                                Object stockUnit = ((JSONObject) contents).get("stock_unit");//库存单位
                                Object demolitionState = ((JSONObject) contents).get("demolition_state");//是否拆零

//                    HxBasicGoods goodsid = hxBasicGoodsService.lambdaQuery()
//                            .eq(HxBasicGoods::getGoodsXlbId, String.valueOf(id))
//                            .one();
//                   if (goodsid == null){

                                hxBasicGoodsParam.setGoodsXlbId(String.valueOf(id));
                                hxBasicGoodsParam.setGoodsName(String.valueOf(name));
                                hxBasicGoodsParam.setGoodsPcode69(String.valueOf(barCode));
                                hxBasicGoodsParam.setGoodsNumber(String.valueOf(code));
                                if (ToolUtil.isNotEmpty(weightSpec.toString())&&!weightSpec.toString().equals("null")) {
                                    hxBasicGoodsParam.setGoodsSpecs(String.valueOf(weightSpec));
                                }
//                    hxBasicGoodsService.findgoods(hxBasicGoodsParam);


                                hxBasicGoodsParam.setJibenUnit(String.valueOf(unit));
                                hxBasicGoodsParam.setKcUnit(String.valueOf(stockUnit));
                                hxBasicGoodsParam.setKcRate(String.valueOf(stockRatio));
                                hxBasicGoodsParam.setCgUnit(String.valueOf(purchaseUnit));
                                hxBasicGoodsParam.setCgRate(String.valueOf(purchaseRatio));
                                hxBasicGoodsParam.setPfRate(String.valueOf(wholesaleRatio));
                                hxBasicGoodsParam.setPfUnit(String.valueOf(wholesaleUnit));
                                hxBasicGoodsParam.setPsRate(String.valueOf(deliveryRatio));
                                hxBasicGoodsParam.setPsUnit(String.valueOf(deliveryUnit));
                                hxBasicGoodsParam.setCreateTime(new Date());
                                hxBasicGoodsParam.setCreateName("系统");
                                hxBasicGoodsParam.setDeliverId(r.getDeliverId());
                                hxBasicGoodsParam.setDeptId(r.getDeptId());
                                hxBasicGoodsParam.setGoodsCustomerName(r.getCustomerName());
                                hxBasicGoodsParam.setGoodsCustomerId(r.getId());
                                hxBasicGoodsParam.setGoodsBottom("10");
                                hxBasicGoodsParam.setGoodsLamination("10");
                                hxBasicGoodsParam.setGoodsTraylayer("1");
                                hxBasicGoodsParam.setGoodsSupportvolume("100");

                                hxBasicGoodsParam.setGoodsChargingCg(String.valueOf(purchasePrice));
                                hxBasicGoodsParam.setGoodsChargingPf(String.valueOf(wholesalePrice));
                                hxBasicGoodsParam.setGoodsChargingPs(String.valueOf(deliveryPrice));
                                hxBasicGoodsParam.setAnquanNum("14");
                                if (ToolUtil.isNotEmpty(expireTypeNum.toString())&&!expireTypeNum.toString().equals("null")) {
                                    if (expireType.toString().equals("2")){
                                        hxBasicGoodsParam.setGoodsWarranty(String.valueOf(expireTypeNum));
                                    }
                                    if (expireType.toString().equals("1")){
                                        hxBasicGoodsParam.setGoodsWarranty(String.valueOf((int)expireTypeNum/30));
                                    }
                                }else{
                                    hxBasicGoodsParam.setGoodsWarranty("36");
                                }

                                if (ToolUtil.isNotEmpty(width.toString())&&!width.toString().equals("null")) {
                                    hxBasicGoodsParam.setWidth(String.valueOf(width));

                                }else{
                                    hxBasicGoodsParam.setWidth("0.1");
                                }
                                if (ToolUtil.isNotEmpty(height.toString())&&!height.toString().equals("null")) {
                                    hxBasicGoodsParam.setHeight(String.valueOf(height));
                                }else{
                                    hxBasicGoodsParam.setHeight("0.1");
                                }
                                if (ToolUtil.isNotEmpty(length.toString())&&!length.toString().equals("null")) {
                                    hxBasicGoodsParam.setLength(String.valueOf(length));
                                }else{
                                    hxBasicGoodsParam.setLength("0.1");
                                }
                                if (ToolUtil.isNotEmpty(purchaseVolume.toString())&&!purchaseVolume.toString().equals("null")) {
                                    BigDecimal volumeRate = new BigDecimal(purchaseVolume.toString());
                                    hxBasicGoodsParam.setGoodsVolume(volumeRate.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                                }else{
                                    hxBasicGoodsParam.setGoodsVolume("0.1");
                                }

                                if (ToolUtil.isNotEmpty(netWeight.toString())&&!netWeight.toString().equals("null")) {
                                    hxBasicGoodsParam.setGoodsWeight(String.valueOf(netWeight));

                                }else{
                                    hxBasicGoodsParam.setGoodsWeight("0.1");
                                }

//                                HxBasicGoodsCodeResult  hxBasicGoodsCode = goodsCodeMap.get(categoryId.toString());
//                                if (hxBasicGoodsCode != null) {
//                                    hxBasicGoodsParam.setGoodsBigtype(hxBasicGoodsCode.getCodeName());
//                                    hxBasicGoodsParam.setGoodsBigtypedictId((long)hxBasicGoodsCode.getId());
//
//                                }else{
//                                    hxBasicGoodsParam.setGoodsBigtypedictId(0L);
//
//                                }

                                if (ToolUtil.isNotEmpty(dateInType.toString())&&!dateInType.toString().equals("null")){
                                    if (String.valueOf(demolitionState).equals("true")){
                                        hxBasicGoodsParam.setDismantlingParts("是");
                                    }
                                    if (String.valueOf(demolitionState).equals("false")){
                                        hxBasicGoodsParam.setDismantlingParts("否");
                                    }
                                }else{
                                    hxBasicGoodsParam.setDismantlingParts("");
                                }


                                batchToAdd.add(hxBasicGoodsParam);
                            }
                        }

                    }
                }

                // 创建一个Map<商品编号, HxBasicGoods>，便于通过商品编号查找
                Map<String, HxBasicGoods> batchToAddMap = new HashMap<>();
                for (HxBasicGoods good : batchToAdd) {
                    batchToAddMap.put(good.getGoodsXlbId(), good);
                }

                List<HxBasicGoods> goodsDifferent = new ArrayList<>();
                List<HxBasicGoods> goodswarrantyDifferent = new ArrayList<>();

                List<HxBasicGoods> goodsNameGoodsSpecDifferent = new ArrayList<>();
                List<HxBasicGoods> goodsRates = new ArrayList<>();

                // 遍历list，进行换算率比较
                for (HxBasicGoodsResult sourceGood : list) {
                    HxBasicGoods targetGood = batchToAddMap.get(sourceGood.getGoodsXlbId());
                    if (targetGood != null) {
                        String sourceDismantlingParts = sourceGood.getDismantlingParts();
                        String targetDismantlingParts = targetGood.getDismantlingParts();

                        if (sourceDismantlingParts != null && targetDismantlingParts != null && !sourceDismantlingParts.equals(targetDismantlingParts)) {
                            goodsDifferent.add(targetGood);
                        }

                        String goodsWarranty1 = sourceGood.getGoodsWarranty();
                        String goodsWarranty2 = targetGood.getGoodsWarranty();


                        if (goodsWarranty1 != null && goodsWarranty2 != null && !goodsWarranty1.equals(goodsWarranty2)) {
                            goodswarrantyDifferent.add(targetGood);
                        }

                        // 检查商品名称和商品规格是否一致
                        String sourceGoodsName = sourceGood.getGoodsName();
                        String targetGoodsName = targetGood.getGoodsName();
                        String sourceGoodsSpec = sourceGood.getGoodsSpecs();
                        String targetGoodsSpec = targetGood.getGoodsSpecs();
                        String sourceGoodsNumber = sourceGood.getGoodsNumber(); // 获取源商品编号
                        String targetGoodsNumber = targetGood.getGoodsNumber(); // 获取目标商品编号

                        if ((sourceGoodsName != null && targetGoodsName != null && !sourceGoodsName.equals(targetGoodsName)) ||
                                (sourceGoodsSpec != null && targetGoodsSpec != null && !sourceGoodsSpec.equals(targetGoodsSpec)) ||
                                (sourceGoodsNumber != null && targetGoodsNumber != null && !sourceGoodsNumber.equals(targetGoodsNumber))) {
                            // 更新商品名称、商品规格和商品编号
                            goodsNameGoodsSpecDifferent.add(targetGood);
                        }



                        // 比较每种换算率
                        BigDecimal sourceKcRate = new BigDecimal(sourceGood.getKcRate());
                        String sourceUnitName = sourceGood.getKcUnit();
                        BigDecimal targetKcRate = new BigDecimal(targetGood.getKcRate());
                        String targetUnitName = targetGood.getKcUnit();

                        BigDecimal sourceCgRate = new BigDecimal(sourceGood.getCgRate());
                        String sourceCgUnitName = sourceGood.getCgUnit();
                        BigDecimal targetCgRate = new BigDecimal(targetGood.getCgRate());
                        String targetCgUnitName = targetGood.getCgUnit();

                        BigDecimal sourcePfRate = new BigDecimal(sourceGood.getPfRate());
                        String sourcePfUnitName = sourceGood.getPfUnit();
                        BigDecimal targetPfRate = new BigDecimal(targetGood.getPfRate());
                        String targetPfUnitName = targetGood.getPfUnit();

                        BigDecimal sourcePsRate = new BigDecimal(sourceGood.getPsRate());
                        String sourcePsUnitName = sourceGood.getPsUnit();
                        BigDecimal targetPsRate = new BigDecimal(targetGood.getPsRate());
                        String targetPsUnitName = targetGood.getPsUnit();

                        String sourceJibenUnit = sourceGood.getJibenUnit();
                        String targetJibenUnit = targetGood.getJibenUnit();


//                        boolean isEqual = sourceKcRate.compareTo(targetKcRate) == 0 &&
//                                sourceCgRate.compareTo(targetCgRate) == 0 &&
//                                sourcePfRate.compareTo(targetPfRate) == 0 &&
//                                sourcePsRate.compareTo(targetPsRate) == 0;
                        boolean isKcEqual = sourceKcRate.compareTo(targetKcRate) == 0 && sourceUnitName.equals(targetUnitName);
                        boolean isCgEqual = sourceCgRate.compareTo(targetCgRate) == 0 && sourceCgUnitName.equals(targetCgUnitName);
                        boolean isPfEqual = sourcePfRate.compareTo(targetPfRate) == 0 && sourcePfUnitName.equals(targetPfUnitName);
                        boolean isPsEqual = sourcePsRate.compareTo(targetPsRate) == 0 && sourcePsUnitName.equals(targetPsUnitName);
                        boolean isJibenUnitEqual = sourceJibenUnit.equals(targetJibenUnit);
// 综合判断
                        boolean isEqual = isKcEqual && isCgEqual && isPfEqual && isPsEqual && isJibenUnitEqual;
                        if (!isEqual) {
                            goodsRates.add(targetGood);
                        }


                    }

                }
                if (goodsDifferent.size() > 0){
                    // 调用接口，更新是否拆零字段
                    for (HxBasicGoods good : goodsDifferent) {
                        HxBasicGoodsParam hxBasicGoodsParam = new HxBasicGoodsParam();
                        hxBasicGoodsParam.setGoodsNumber(good.getGoodsNumber());
                        hxBasicGoodsParam.setDismantlingParts(good.getDismantlingParts());
                        hxBasicGoodsParam.setGoodsCustomerId(r.getId());
                        hxBasicGoodsParam.setDeptId(r.getDeptId());
                        hxBasicGoodsParam.setDeliverId(r.getDeliverId());
                        hxBasicGoodsService.updategoodsrate1(hxBasicGoodsParam);

                    }

                }
                if (goodswarrantyDifferent.size() > 0){
                    // 调用接口，更新保质期字段
                    for (HxBasicGoods good : goodswarrantyDifferent) {
                        HxBasicGoodsParam hxBasicGoodsParam = new HxBasicGoodsParam();
                        hxBasicGoodsParam.setGoodsNumber(good.getGoodsNumber());
                        hxBasicGoodsParam.setGoodsWarranty(good.getGoodsWarranty());
                        hxBasicGoodsParam.setGoodsCustomerId(r.getId());
                        hxBasicGoodsParam.setDeptId(r.getDeptId());
                        hxBasicGoodsParam.setDeliverId(r.getDeliverId());
                        hxBasicGoodsService.updategoodsrate2(hxBasicGoodsParam);

                    }

                }
                if (goodsNameGoodsSpecDifferent.size() > 0){
                      // 调用接口，更新商品名称和商品规格
                    for (HxBasicGoods good : goodsNameGoodsSpecDifferent) {
                        HxBasicGoodsParam hxBasicGoodsParam = new HxBasicGoodsParam();
                        hxBasicGoodsParam.setGoodsNumber(good.getGoodsNumber());
                        hxBasicGoodsParam.setGoodsName(good.getGoodsName());
                        hxBasicGoodsParam.setGoodsSpecs(good.getGoodsSpecs());
                        hxBasicGoodsParam.setGoodsCustomerId(r.getId());
                        hxBasicGoodsParam.setDeptId(r.getDeptId());
                        hxBasicGoodsParam.setDeliverId(r.getDeliverId());
                        hxBasicGoodsParam.setGoodsXlbId(good.getGoodsXlbId());
                        hxBasicGoodsService.updategoodsrate3(hxBasicGoodsParam);

                    }

                }

                if (goodsRates.size() > 0){
                    // 调用接口，更新换算率
                    for (HxBasicGoods good : goodsRates) {
                        HxBasicGoodsParam hxBasicGoodsParam = new HxBasicGoodsParam();
                        hxBasicGoodsParam.setGoodsNumber(good.getGoodsNumber());
                        hxBasicGoodsParam.setKcRate(good.getKcRate());
                        hxBasicGoodsParam.setKcUnit(good.getKcUnit());
                        hxBasicGoodsParam.setCgRate(good.getCgRate());
                        hxBasicGoodsParam.setCgUnit(good.getCgUnit());
                        hxBasicGoodsParam.setPfRate(good.getPfRate());
                        hxBasicGoodsParam.setPfUnit(good.getPfUnit());
                        hxBasicGoodsParam.setPsRate(good.getPsRate());
                        hxBasicGoodsParam.setPsUnit(good.getPsUnit());
                        hxBasicGoodsParam.setJibenUnit(good.getJibenUnit());
                        hxBasicGoodsParam.setGoodsCustomerId(r.getId());
                        hxBasicGoodsParam.setDeptId(r.getDeptId());
                        hxBasicGoodsParam.setDeliverId(r.getDeliverId());
                        hxBasicGoodsService.updategoodsrate(hxBasicGoodsParam);

                    }

                }

            }
        }
    }
    @Override
    public void updategoodsrate(HxBasicGoodsParam hxBasicGoodsParam) {
         this.baseMapper.updategoodsrate(hxBasicGoodsParam);
    }
    @Override
    public void updategoodsrate1(HxBasicGoodsParam hxBasicGoodsParam) {
        this.baseMapper.updategoodsrate1(hxBasicGoodsParam);
    }
    @Override
    public void updategoodsrate2(HxBasicGoodsParam hxBasicGoodsParam) {
        this.baseMapper.updategoodsrate2(hxBasicGoodsParam);
    }
    @Override
    public void updategoodsrate3(HxBasicGoodsParam hxBasicGoodsParam) {
        this.baseMapper.updategoodsrate3(hxBasicGoodsParam);
    }

    @Override
    public LayuiPageInfo findWHPageBySpec(HxBasicGoodsParam hxBasicGoodsParam) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customWhPageList(pageContext, hxBasicGoodsParam);
        return LayuiPageFactory.createPageInfo(page);
    }
}

